<?php


namespace App\Services\Base;

use App\Constants\AuthType;
use Illuminate\Support\Facades\Log;

class HelpService
{

    public static function log(\Throwable $e, $force = false, $data = "", $channel = "")
    {
        if ($force || !is_numeric($e->getCode()) || $e->getCode() <= 0 || $e->getCode() > M_END) {
            $s = sprintf("%s:%d %s (%d) [%s] [%s]", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e), var_export($data, 1));
            if ($channel) {
                Log::channel($channel)->error($s);
            } else {
                Log::error($s);
            }
        }
    }

    public static function forceLog(\Throwable $e, $data = "", $channel = "")
    {
        $s = sprintf("%s:%d %s (%d) [%s] [%s]", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e), var_export($data, 1));
        if ($channel) {
            Log::channel($channel)->error($s);
        } else {
            Log::error($s);
        }

        return $s;
    }

    public static function checkEmailOrPhone($name, $type)
    {
        switch ($type) {
            case AuthType::CHECK_PHONE:
                if (!g_check_phone($name)) {
                    throw new \Exception('', 1012);
                }
                break;
            case AuthType::CHECK_EMAIL:
                if (!g_check_email($name)) {
                    throw new \Exception('', 1013);
                }
                break;
        }
    }


    public static function contentRead($key, $uid, $id)
    {
        $ids = CacheService::hGet($key, $uid);
        $idsArr = [];
        if ($ids) {
            $idsArr = explode(",", $ids);
        }
        $already = true;
        if (!in_array($id, $idsArr)) {
            $idsArr[] = $id;
            $already = false;
            CacheService::hSet($key, $uid, implode(",", $idsArr));
        }
        return $already;
    }

    public static function contentReadCheck($key, $uid, $id, $ids = [])
    {
        if (!$ids) {
            $ids = CacheService::hGet($key, $uid);
        }
        if ($ids) {
            $ids_arr = explode(",", $ids);
            if (in_array($id, $ids_arr)) {
                return true;
            } else {
                return false;
            }
        }

        return false;
    }


}
